﻿using Contract.Domain;
using MediatR;
using Newtonsoft.Json;
using PublicCommon;
using System.Collections.Generic;
using Trace.Infrastructure.Repository;
using Trace.WebApi.Commands;

namespace Trace.WebApi.CommandHandler
{
    public class UpdTraceCommandHandler : IRequestHandler<UpdTraceCommands, int>
    {
        private readonly IRepository<Contract.Domain.Contract> repository;
        private readonly Cross_services_Helper cross_services_helper;
        private readonly IRepository<Tail> repository1;

        public UpdTraceCommandHandler(IRepository<Contract.Domain.Contract> repository, Cross_services_Helper cross_services_helper, IRepository<Tail> repository1)
        {
            this.repository = repository;
            this.cross_services_helper = cross_services_helper;
            this.repository1 = repository1;
        }

        public async Task<int> Handle(UpdTraceCommands request, CancellationToken cancellationToken)
        {
            var ind = await repository.GetAsync(x => x.ContractNumber == request.ContractNumber);
            ind.FreightStatus = request.FreightStatus;
            ind.Abnormity = request.Abnormity;
            ind.UpdateDate = DateTime.Now;
            int inf = await repository.UpdateAsync(ind);

            var res = await cross_services_helper.Get($"http://10.31.60.9:8000/LongLine/api/LineInfo/GetLineRoute");
            var line = JsonConvert.DeserializeObject<List<LineDto>>(res);
            var inds = line.FirstOrDefault(x => x.Id == ind.Route);
            if (request.Tail == 1)
            {
                Tail tail = new Tail();
                tail.ContractNumber = ind.ContractNumber;
                tail.DateTime = ind.UpdateDate;
                tail.TrackingState = $"货物已在【{inds.QAddress}】提货";
                tail.license = "京A36588";
                await repository1.AddAsync(tail);
            }
            else if(request.Tail == 2)
            {
                Tail tail = new Tail();
                tail.ContractNumber = ind.ContractNumber;
                tail.DateTime = DateTime.Now;
                tail.license = "京A36588";
                tail.TrackingState = $"货物已送达【{inds.Address}】";
                tail.GoodsState = "您的货物已经安全送达目的地。";
                await repository1.AddAsync(tail);
                Tail tail2 = new Tail();
                tail2.ContractNumber = ind.ContractNumber;
                tail2.TrackingState = $"货物已在【{inds.Address}】签收";
                tail2.Signed = inds.Address;
                tail2.DateTime = DateTime.Now;
                tail2.GoodsState = "您的货物已经妥投，感谢在本次合作中的支持，期待再次为您服务。";
                await repository1.AddAsync(tail2);
            }
            return inf;
        }
    }
}
